package com.yang.framework.aop.log;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;

@Slf4j
@Aspect
public class ApiOperationLogAspect {

    /**
     * 定义按照注解@ApiOperationLog进行切入的表达式
     */
    @Pointcut("@annotation(com.yang.framework.aop.log.ApiOperationLog)")
    public void apiOperationLogPointcut() {}

    @Around("apiOperationLogPointcut()")
    public Object aroundWork(ProceedingJoinPoint joinPoint) throws Throwable {
        //  开始时间
        long startTime = System.currentTimeMillis();

        //  拿到方法签名
        MethodSignature methodSignature = (MethodSignature) joinPoint.getSignature();
        //  拿到方法
        Method method = methodSignature.getMethod();
        //  拿到日志注解
        ApiOperationLog apiOperationLog = method.getAnnotation(ApiOperationLog.class);

        StringBuilder sb = new StringBuilder();
        Parameter[] parameters = method.getParameters();
        Object[] args = joinPoint.getArgs();
        for (int i = 0; i < parameters.length; i++) {
            String key = parameters[i].getName();
            Object value = args[i];
            sb.append(key + "=" + value + ", ");
        }
        if (sb.length() > 2) {
            sb.delete(sb.length() -2,sb.length() - 1);
        }

        //  打印日志
        log.info("====== 请求开始：[{}]，请求类：{}，请求方法：{} , 传入参数：{}======",
                apiOperationLog.value(),joinPoint.getTarget().getClass().getSimpleName(),method.getName(), sb
        );

        Object result = joinPoint.proceed();

        //  结束时间
        long endTime = System.currentTimeMillis();

        log.info("====== 请求结束：[{}]， 返回数据：{}， 方法耗时：{}ms ======",
                apiOperationLog.value(),result, endTime - startTime
        );

        return result;
    }


}
